package main

import (
	"bufio"
	"fmt"
	"github.com/tealeg/xlsx"
	"image"
	"image/color"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

var styleCache = make(map[string]*xlsx.Style)

type RGB struct {
	red, green, blue int64
}

type HEX struct {
	str string
}

func t2x(t int64) string {
	result := strconv.FormatInt(t, 16)
	if len(result) == 1 {
		result = "0" + result
	}
	return result
}

func (color RGB) rgb2hex() HEX {
	r := t2x(color.red)
	g := t2x(color.green)
	b := t2x(color.blue)
	return HEX{r + g + b}
}

var picWidth, picHeight int
var rgbaDataList [][]color.Color

func main() {
	println("====================  开始img 转 excel ===================")
	file := xlsx.NewFile()
	filepath.Walk("./img",
		func(path string, f os.FileInfo, err error) error {
			if f == nil {
				return err
			}
			if f.IsDir() {
				return nil
			}
			if strings.Contains(f.Name(), ".jpg") || strings.Contains(f.Name(), ".png") {
				fmt.Printf("开始转换[%s]\n", f.Name())

				readPncPic(file, f)
			}

			return nil
		})
	file.Save("out.xlsx")
}

func readPncPic(xf *xlsx.File, file os.FileInfo) {
	sheet, err := xf.AddSheet(file.Name())
	if err != nil {
		panic(err.Error())
	}

	//读取本地文件
	f, err := os.Open("./img/" + file.Name())
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	g, _, err := image.Decode(bufio.NewReader(f))
	if err != nil {
		log.Fatal(err)
		return
	}
	rect := g.Bounds()
	size := rect.Size()
	picWidth = size.X
	picHeight = size.Y
	rgbaDataList = [][]color.Color{}

	for y := 0; y < picHeight; y++ {
		fmt.Printf("进度%f\n", float64(y)/float64(picHeight))
		row := sheet.AddRow()
		row.SetHeight(80)
		for x := 0; x < picWidth; x++ {
			cell := row.AddCell()
			pixelItem := g.At(x, y)
			r, g, b, _ := pixelItem.RGBA()
			rgb := &RGB{int64(r >> 8), int64(g >> 8), int64(b >> 8)}
			if v, ok := styleCache[rgb.rgb2hex().str]; ok {
				cell.SetStyle(v)
			} else {
				style := xlsx.NewStyle()
				fill := *xlsx.NewFill("solid", rgb.rgb2hex().str, "")
				style.Fill = fill
				styleCache[rgb.rgb2hex().str] = style
				cell.SetStyle(style)
			}
		}

	}

	fmt.Printf("文件[%s]转换结束\n", file.Name())
}
